package cc.aliza.lib.mongo.core.decoder;

import cc.aliza.lib.mongo.core.annotations.Embed;
import cc.aliza.lib.mongo.core.utils.FieldUtil;
import cc.aliza.lib.mongo.core.utils.MapperUtil;
import org.bson.Document;

import java.lang.reflect.Field;

/**
 * 『给时光以生命·给岁月以文明』
 *
 * @author Zhang Jing (byrdkm17@gmail.com).
 */
@SuppressWarnings("unchecked")
public class EmbedDecoder extends AbstractDecoder {

    public EmbedDecoder(Document document, Field field) {
        super(field);
        Embed embed = field.getAnnotation(Embed.class);
        value = document.get(getFieldRealName(embed.name()));
    }

    @Override
    public void decode(Object obj) {
        Document document = (Document) value;
        Class clazz = FieldUtil.getRealType(field, document);
        FieldUtil.set(obj, field, MapperUtil.fromDocument(clazz, document));
    }
}
